package de.bbl.android.fragment.DataCenter.Spielplan;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import de.bbl.android.BBLAndroidFragmentActivity;
import de.bbl.android.R;
import de.bbl.android.adapter.DataCenter.DataCenterSpieltagArrayAdapter;
import de.bbl.android.adapter.GameCenter.GameCenterArrayAdapter;
import de.bbl.android.classes.CompletePlaydays;
import de.bbl.android.classes.Match;
import de.bbl.android.tools.Tools;
import de.bbl.android.tools.XmlParseGameDayTools;
import de.bbl.android.tools.XmlParseGamePlanTools;

public class DataCenterSpielplanFragment extends ListFragment {
	Activity activity;
	Match[] currentLoaded = null;
	CompletePlaydays currentLoadedPlaydays = null;
	private boolean finished = true;
	private boolean isDetached = false;
	
	private final int CHRONOLOGISCH = 0x1;
	private final int SPIELTAG = 0x2;
	private final int QUARTERFINAL = 0x3;
	private final int SEMIFINAL = 0x4;
	private final int FINAL = 0x5;
	
	// startview = SPIELTAG
	private int mCurrentViewId = 0x2;

	boolean mDualPane;

	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = getActivity();
        if (savedInstanceState == null || currentLoaded == null || currentLoadedPlaydays == null) {
        	RefreshData();
        }
        
        View newsExpanded = getActivity().findViewById(R.id.fragment_side_content);
        mDualPane = newsExpanded != null && newsExpanded.getVisibility() == View.VISIBLE;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
    	inflater.inflate(R.menu.activity_bblmain_gameplan, menu);
    	
    	// remove Refresh from OptionsMenu cause is implemented in titlebar
    	if (android.os.Build.VERSION.SDK_INT < 11)
    		menu.getItem(0).setVisible(false);
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
	}

    @Override    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.Chronologisch:
        	mCurrentViewId = CHRONOLOGISCH;
        	RefreshData();
        	break;
        case R.id.Spieltag:
        	mCurrentViewId = SPIELTAG;
        	RefreshData();
        	break;
        case R.id.Playoffs_Viertelfinale:
        	mCurrentViewId = QUARTERFINAL;
        	RefreshData();
        	break;
        case R.id.Playoffs_Halbfinale:
        	mCurrentViewId = SEMIFINAL;
        	RefreshData();
        	break;
        case R.id.Playoffs_Finale:
        	mCurrentViewId = FINAL;
        	RefreshData();
        	break;
        case R.id.Refresh:
          	RefreshData();
            	break;
        }
        return true;
    }
	
    public void RefreshData() {
        setHasOptionsMenu(true);
        if (activity != null) {
    		startProgress(activity.getCurrentFocus());
        }
    }

	private void loadData() {
		String[] dataArrayUrl = getResources().getStringArray(R.array.Data_Files_Url);
		String[] dataArray = getResources().getStringArray(R.array.Data_Files);
		String dataUrl = "";
		String data = "";
		if (mCurrentViewId == CHRONOLOGISCH) {
			dataUrl = dataArrayUrl[BBLAndroidFragmentActivity.DATA_ALLMATCHES];
			data = dataArray[BBLAndroidFragmentActivity.DATA_ALLMATCHES];
		} else {
			dataUrl = dataArrayUrl[BBLAndroidFragmentActivity.DATA_MATCHDAY_NUMBER];
			data = dataArray[BBLAndroidFragmentActivity.DATA_MATCHDAY_NUMBER];
		}
		Tools.getGamedayData(getResources().getString(R.string.main_url), dataUrl, data, BBLAndroidFragmentActivity.bbl_temp_sd_path);
			
	}
    
    private void startProgress(final View view) {
    	final int tempCurrentViewID = mCurrentViewId;
    	final Handler refresh = new Handler(Looper.getMainLooper());
    	Runnable runnable = new Runnable() {			
			public void run() {
				setFinished(false);
				String[] dataArray = getResources().getStringArray(R.array.Data_Files);
				loadData();
				if (tempCurrentViewID == CHRONOLOGISCH)
					currentLoaded = XmlParseGameDayTools.XmlParseGameDay(BBLAndroidFragmentActivity.bbl_temp_sd_path + dataArray[BBLAndroidFragmentActivity.DATA_ALLMATCHES]);
				else 
					currentLoadedPlaydays = XmlParseGamePlanTools.XmlParseGameDay(BBLAndroidFragmentActivity.bbl_temp_sd_path + dataArray[BBLAndroidFragmentActivity.DATA_MATCHDAY_NUMBER]);
		    	refresh.post(new Runnable() {
					public void run() {
						if (! isDetached()) {
							representSpielplanData(view);
							setFinished(true);
						}
					}
				});				
			}
		};		
		new Thread(runnable).start();
    }

	public boolean isFinished() {
		return finished;
	}

	public void setFinished(boolean finished) {
		this.finished = finished;
	}

	private void representSpielplanData(View view) {
		Log.d("bbl-debug", "Spielplan Fagrment detached: " + isDetached);
		if (mCurrentViewId == CHRONOLOGISCH && currentLoaded != null && ! isDetached)
		{
			GameCenterArrayAdapter adapter = new GameCenterArrayAdapter(activity, currentLoaded);
			setListAdapter(adapter); 
		} else if (mCurrentViewId == SPIELTAG && currentLoadedPlaydays != null && ! isDetached) {
			DataCenterSpieltagArrayAdapter adapter = new DataCenterSpieltagArrayAdapter(activity, currentLoadedPlaydays.getLeagueGames());
			adapter.setCompetitionId("1");
			setListAdapter(adapter);
		} else if (mCurrentViewId == QUARTERFINAL && currentLoadedPlaydays != null && ! isDetached) {
			DataCenterSpieltagArrayAdapter adapter = new DataCenterSpieltagArrayAdapter(activity, currentLoadedPlaydays.getPlayoffQuarterFinal());
			adapter.setCompetitionId("2");
			setListAdapter(adapter);
		} else if (mCurrentViewId == SEMIFINAL && currentLoadedPlaydays != null && ! isDetached) {
			DataCenterSpieltagArrayAdapter adapter = new DataCenterSpieltagArrayAdapter(activity, currentLoadedPlaydays.getPlayoffSemiFinal());
			adapter.setCompetitionId("3");
			setListAdapter(adapter);
		} else if (mCurrentViewId == FINAL && currentLoadedPlaydays != null && ! isDetached) {
			DataCenterSpieltagArrayAdapter adapter = new DataCenterSpieltagArrayAdapter(activity, currentLoadedPlaydays.getPlayoffFinal());
			adapter.setCompetitionId("4");
			setListAdapter(adapter);
		} else {
			// Problem???
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, final int position, long id) {
		if (mCurrentViewId == SPIELTAG) {
		   	final FragmentManager  fm = getFragmentManager();
	    	FragmentTransaction ft = fm.beginTransaction();
			DataCenterSpielplanSpieltagFragment ssf = new DataCenterSpielplanSpieltagFragment();
			ssf.setCompetitionId("1");
			ssf.setMatchDay(currentLoadedPlaydays.getLeagueGames()[position].getPlayDayNumber());
			if (mDualPane)
				ft.replace(R.id.fragment_side_content, ssf, "datacenter-spielplan-spieltag");
			else
				ft.replace(R.id.fragment_content, ssf, "datacenter-spielplan-spieltag");
	    	ft.addToBackStack(getTag());
	    	ft.commit();
		} else if (mCurrentViewId == QUARTERFINAL) {
		   	final FragmentManager  fm = getFragmentManager();
	    	FragmentTransaction ft = fm.beginTransaction();
			DataCenterSpielplanSpieltagFragment ssf = new DataCenterSpielplanSpieltagFragment();
			ssf.setMatchDay(currentLoadedPlaydays.getPlayoffQuarterFinal()[position].getPlayDayNumber());
			ssf.setCompetitionId("2");
			if (mDualPane)
				ft.replace(R.id.fragment_side_content, ssf, "datacenter-spielplan-spieltag");
			else
				ft.replace(R.id.fragment_content, ssf, "datacenter-spielplan-spieltag");
	    	ft.addToBackStack(getTag());
	    	ft.commit();
		} else if (mCurrentViewId == SEMIFINAL) {
		   	final FragmentManager  fm = getFragmentManager();
	    	FragmentTransaction ft = fm.beginTransaction();
			DataCenterSpielplanSpieltagFragment ssf = new DataCenterSpielplanSpieltagFragment();
			ssf.setMatchDay(currentLoadedPlaydays.getPlayoffSemiFinal()[position].getPlayDayNumber());
			ssf.setCompetitionId("3");
			if (mDualPane)
				ft.replace(R.id.fragment_side_content, ssf, "datacenter-spielplan-spieltag");
			else
				ft.replace(R.id.fragment_content, ssf, "datacenter-spielplan-spieltag");
	    	ft.addToBackStack(getTag());
	    	ft.commit();
		} else if (mCurrentViewId == FINAL) {
		   	final FragmentManager  fm = getFragmentManager();
	    	FragmentTransaction ft = fm.beginTransaction();
			DataCenterSpielplanSpieltagFragment ssf = new DataCenterSpielplanSpieltagFragment();
			ssf.setCompetitionId("4");
			ssf.setMatchDay(currentLoadedPlaydays.getPlayoffFinal()[position].getPlayDayNumber());
			if (mDualPane)
				ft.replace(R.id.fragment_side_content, ssf, "datacenter-spielplan-spieltag");
			else
				ft.replace(R.id.fragment_content, ssf, "datacenter-spielplan-spieltag");
	    	ft.addToBackStack(getTag());
	    	ft.commit();
		}

	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		isDetached = true;
	}
	
}
